package com.woniuxy.meal.controller;


import cn.hutool.core.io.FileUtil;
import com.woniuxy.meal.common.Result;
import com.woniuxy.meal.config.GetTypeByHead;
import com.woniuxy.meal.entity.CommentInfo;
import com.woniuxy.meal.form.AddCommentForm;
import com.woniuxy.meal.form.SearchCommentForm;
import com.woniuxy.meal.service.CommentInfoService;
import com.woniuxy.meal.service.dto.CommentInfoDto;
import com.woniuxy.meal.util.OSSUtil;
import com.woniuxy.meal.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 评价信息表 前端控制器
 * </p>
 *
 * @author zz
 * @since 2023年06月12日
 */
@RestController
@RequestMapping("/commentInfo")
@Api(tags = "评论相关接口")
public class CommentInfoController {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CommentInfoService service;
    @Autowired
    private OSSUtil ossUtil;

    @PostMapping("/insert")
    @ApiOperation("用户发布评论")
    public Result insert(@Valid @RequestBody AddCommentForm form, @RequestHeader String token) throws Exception {
        Long userId = redisUtil.getUserIdByToken(token);
        CommentInfo commentInfo=service.add(form,userId);
        return Result.success(200,"发布评论成功",commentInfo);
    }

    @GetMapping("/del")
    @ApiOperation("用户删除评论")
    public Result del(Long commentId, @RequestHeader String token){
        Long userId = redisUtil.getUserIdByToken(token);
        service.del(commentId,userId);
        return Result.success(200,"删除评论成功",null);
    }

    @GetMapping("/search")
    @ApiOperation("展示评论")
    public Result getComment( SearchCommentForm form){
        List<CommentInfoDto> dto=service.getComment(form);
        return Result.success(200,"展示评论成功",dto);
    }

    @PostMapping("/upload")
    @ApiOperation("上传图片")
    public Result upload(MultipartFile file) throws Exception {
        String fileType = GetTypeByHead.getFileHeader(file);
        if ( !(fileType.equals("jpg")|| fileType.equals("png")|| fileType.equals("tif") ||fileType.equals("jpeg"))){
            throw new Exception("请上传图片类型的文件");
        }
        InputStream is = file.getInputStream();
        String fileOriginalFilename = file.getOriginalFilename();
        String suffix = FileUtil.getSuffix(fileOriginalFilename);
        String newFileName = UUID.randomUUID().toString().replace("_","");
        String url = ossUtil.uploadFile(is, newFileName + "." + suffix, "bucket-book-fjx");
        return Result.success(200,"上传图片成功",url);
        //https://bucket-book-fjx.oss-cn-chengdu.aliyuncs.com/606b7e7c-addf-4e65-8b2f-7e4bea2b4157.jpeg
    }

}

